<?php
use Mapper\MemberModel as MemberMapper;
use Mapper\FriendModel as FriendMapper;

class FriendController extends \Base\ApiController {

    /**
     * @desc 取得好友列表(第一步取得好友id, 第二部取得好友的信息)
     *
     * @return false
     */
    public function listAction() {
        $uid           = \Lib\User::getInstance()->id();
        $friendsMapper = FriendMapper::getInstance();
        $friendModels  = $friendsMapper->fetchAll(['member_id' => $uid]);

        if(empty($friendModels)) {
            return \Response::error('还没有添加好友', 20202);
        }

        $friendListIds = [];

        foreach($friendModels as $friendModel) {
            $friendListIds[] = $friendModel->getFriend_id();
        }

        $memberMapper     = MemberMapper::getInstance();
        $friendListModels = $memberMapper->fetchAll(['id' => $friendListIds]);
        $return           = [];

        foreach($friendListModels as $friendModel) {
            $data     = $friendModel->toArray();
            $birthday = $friendModel->getBirthday();
            $age      = date('Y') - date('Y', $birthday) - 1;

            if(date('m', time()) == date('m', $birthday)) {
                if(date('d', time()) > date('d', $birthday)) {
                    ++$age;
                }
            } elseif(date('m', time()) > date('m', $birthday)) {
                ++$age;
            }

            $data['age']       = $age;
            $data['nick_name'] = urldecode($friendModel->getNick_name());
            $return[$friendModel->getLetter()][] = $data;
        }

        return \Response::data($return, '好友列表');
    }

    /**
     * @des 添加好友（一次操作仅能添加一个）
     *
     * @return false
     */
    public function addAction() {
        $uid      = \Lib\User::getInstance()->id();
        $request  = $this->getRequest();
        $friendId = (int)$request->get('fid');

        if(empty($friendId)) {
            return \Response::error('好友id不能为空', 20201);
        }

        $friendsMapper = FriendMapper::getInstance();
        $friendExist   = $friendsMapper->fetch(['member_id' => $uid, 'friend_id' => $friendId]);

        if( !empty($friendExist) ) {
            return Response::error('已经是好友了', 20203);
        }

        $model = new \FriendModel();
        $model->setMember_id($uid);
        $model->setFriend_id($friendId);
        $model->setAdd_time(time());

        try {
            $id = $friendsMapper->insert($model);
            return $id ? \Response::data(null, '添加好友成功') : \Response::error('添加好友失败', 20204);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @des 删除好友（一次操作仅能删除一个）
     *
     * @return false
     */
    public function delAction() {
        $uid      = \Lib\User::getInstance()->id();
        $request  = $this->getRequest();
        $friendId = (int)$request->get('fid');

        if($friendId <= 0) {
            return \Response::error('好友id不能为空', 20101);
        }

        $friendsMapper = FriendMapper::getInstance();

        try {
            $rows = $friendsMapper->del(['member_id' => $uid, 'friend_id' => $friendId]);
            return $rows ? \Response::data($rows, '删除成功') : \Response::error('删除好友失败', 20205);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @des 搜索好友
     * @var (int)$type (1-昵称, 2-账号, 3-手机号)
     * @var (string)$keyWord
     *
     * @return false
     */
    public function searchAction() {
        $uid     = \Lib\User::getInstance()->id();
        $request = $this->getRequest();
        $type    = (int)$request->get('type');
        $keyWord = (string)$request->get('key_word');
        $page    = (int)$request->get('page', 1);
        $prePage = (int)$request->get('pre_page', 15);
        $page    = max(1, $page);
        $prePage = min(30, $prePage);
        $limit   = $prePage;
        $offset  = $limit * ($page - 1);

        if( empty($type) ) {
            return \Response::error('类型不能为空',20200);
        }

        if( $keyWord =='' ) {
            return \Response::error('内容不能为空',20200);
        }

        $memberMapper = MemberMapper::getInstance();

        switch ($type) {
            case 1:
                $where = " nick_name like '%".urlencode($keyWord)."%' ";
                break;
            case 2:
                $where = " id like '%".$keyWord."%' ";
                break;
            case 3:
                $where = " mobile like '%".$keyWord."%' ";
                break;
            default:return \Response::error('类型错误',20200);
        }

        $models = $memberMapper->fetchAll($where,'',$limit,$offset);
        $return = [];

        foreach($models as $model) {
            $data     = $model->toArray();
            $birthday = $model->getBirthday();
            $age      = date('Y') - date('Y', $birthday) - 1;

            if(date('m', time()) == date('m', $birthday)) {
                if(date('d', time()) > date('d', $birthday)) {
                    ++$age;
                }
            } elseif(date('m', time()) > date('m', $birthday)) {
                ++$age;
            }

            $data['age']       = $age;
            $data['nick_name'] = urldecode($model->getNick_name());
            $return[]          = $data;

        }


        return \Response::data($return,'搜索结果');
    }
}
